import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';
import MainLayout from '@/layouts/MainLayout.vue';
import { useUserStore } from '@/stores/userStore';

const routes: Array<RouteRecordRaw> = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/LoginView.vue')
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('@/views/RegisterView.vue')
    },
    {
        path: '/',
        component: MainLayout,
        redirect: '/home', // 默认重定向到首页
        children: [
            {
                path: 'home',
                name: 'Home',
                component: () => import('@/views/HomeView.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'family-trees',
                name: 'FamilyTreeList',
                component: () => import('@/views/FamilyTreeListView.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'family-tree/:id',
                name: 'FamilyTree',
                component: () => import('@/views/FamilyTreeView.vue'),
                meta: { requiresAuth: true },
                props: true
            },
            // 【新增】成员详情页的路由
            {
                path: 'person/:id',
                name: 'PersonDetail',
                component: () => import('@/views/PersonDetailView.vue'),
                meta: { requiresAuth: true },
                props: true
            }
        ]
    }
];

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
});

router.beforeEach((to, from, next) => {
    const userStore = useUserStore();
    const token = userStore.token || localStorage.getItem('token');
    if (to.meta.requiresAuth && !token) {
        next({ name: 'Login' });
    } else {
        next();
    }
});

export default router;
